//
//  GridNode.swift
//  iwe
//
//  Created by zhuxietong on 2018/9/1.
//  Copyright © 2018年 zhuxietong. All rights reserved.
//

import Foundation
import UIKit
import AsyncDisplayKit
import Eelay

open class CapNode: JoCellNode {
    public enum Cap {
        case top
        case bottom
        case none
        case topAndBottom
    }
    public var capType:Cap = .none
    
    public var capCheckIndex:Int = 0
    
    public var row:Int = -1
    open var isFirst:Bool{
        get{
            return row == 0
        }
    }
    open var isLast:Bool{
        get{

            var _is = false
            if let ctr = mo.controller as? ASCollectionContainer{
                let list = ctr.collectionNode.model.get(node: ctr.page_load_section, defaultV: NSMutableArray())
                if(list.count > 0 && ((list.count - 1) == row)){
                    _is = true
                }
                
            }
            return _is
        }
    }
    
    open func increaseCheckIndex(){
        capCheckIndex = capCheckIndex + 1
    }
    open override func mo_model_reload() {
        
        updateCap(model: mo.model)
        if(capCheckIndex >= 2){
            return
        }
        
        switch capType {
        case .topAndBottom:
            if let bottomCell = mo.controller?.__extention["__bottomCap"] as? CapNode{
                if(bottomCell===self){
                    return
                }
                DispatchQueue.main.async(execute: {
                    bottomCell.mo_model_reload()
                    bottomCell.increaseCheckIndex()
                })
            }
            mo.controller?.__extention["__bottomCap"] = self
        case .bottom:
            if let bottomCell = mo.controller?.__extention["__bottomCap"] as? CapNode{
                if(bottomCell===self){
                    return
                }
                DispatchQueue.main.async(execute: {
                    bottomCell.mo_model_reload()
                    bottomCell.increaseCheckIndex()
                })
            }
            mo.controller?.__extention["__bottomCap"] = self
        default:
            break
        }
        
    }
    
    
    
    open func updateCap(model:NSMutableDictionary) {
        
        row = model[int:"__row__",-1]
        
        if isLast && isFirst {
            capType = .topAndBottom
            return
        }
        if(isLast){
            capType = .bottom
            return
        }
        if(isFirst){
            capType = .top
            return
        }
        capType = .none
    }
    
    deinit {
    }
}
